package com.ysw.spring.api_security.idempotent.config;

import cn.hutool.http.ContentType;
import com.ysw.constant.ServiceCodeStatus;
import com.ysw.dto.ResponseResult;
import com.ysw.exception.ServiceException;
import com.ysw.spring.spring_util.json.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author: yu_sw
 * @Description: com.ysw.spring.api_security.idempotent.config
 * @date:2023/3/20 14:33
 */
@Component
public class CheckIdempotentInterceptor implements HandlerInterceptor {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return HandlerInterceptor.super.preHandle(request, response, handler);
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        CheckIdempotent annotation = handlerMethod.getMethod().getAnnotation(CheckIdempotent.class);
        if (null != annotation) {
            try {
                return checkToken(request);
            } catch (ServiceException e) {
                writeJson(response, ResponseResult.fail(e.getCodeStatus()));
            } catch (Exception e) {
                writeJson(response, ResponseResult.fail(ResponseResult.fail("服务器繁忙")));
            }
            return false;
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    private void writeJson(HttpServletResponse response, ResponseResult result) {
        response.reset();
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(400);
        try (final PrintWriter writer = response.getWriter();) {
            writer.print(JsonUtils.objectToString(result));
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public boolean checkToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            throw new ServiceException(ServiceCodeStatus.BASE_VALID_PARAM);
        }
        if (!redisTemplate.delete(token)) {
            throw new ServiceException(ServiceCodeStatus.REPEAT_REQUEST);
        }
        return true;
    }
}
